package com.shop.shoppingmall.controller;

import com.shop.shoppingmall.dao.ShOrderAllDao;
import com.shop.shoppingmall.dao.ShOrderDao;
import com.shop.shoppingmall.entity.ShOrder;
import com.shop.shoppingmall.entity.ShOrderAll;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


@Component
public class TopicMessageListener extends KeyExpirationEventMessageListener {

	@Resource
	private ShOrderDao shOrderDao;
	@Resource
	private ShOrderAllDao shOrderAllDao;

	 public TopicMessageListener(RedisMessageListenerContainer listenerContainer) {
	 	super(listenerContainer);
	    }

	@Override
	public void onMessage(Message message, byte[] pattern) {// 客户端监听订阅的topic，当有消息的时候，会触发该方法
        	byte[] body = message.getBody();// 请使用valueSerializer
        	byte[] channel = message.getChannel();
        	String topic = new String(channel);
        	String itemValue = new String(body);
        	// 请参考配置文件，本例中key，value的序列化方式均为string。
        	System.out.println("topic:"+topic);
        	System.out.println("itemValue:"+itemValue);
        	   String str1=itemValue.substring(0, itemValue.indexOf(","));
        	    String str2=itemValue.substring(str1.length()+1, itemValue.length());
        	    System.out.println("str1"+str1);
        	    System.out.println("str2"+str2);
        	    if(str1.equals("orderNumber")) {
					//System.out.println(str2);
					ShOrder shOrder = shOrderDao.queryOrderNumber(str2);
					if(shOrder == null){
						ShOrderAll shOrderAll1 = shOrderAllDao.selectByOrderAllNum(str2);
						if(shOrderAll1.getOrderStatus().equals("1")){
							shOrderDao.updateOrderAllsStatus(str2);
						}
						List<ShOrder> shOrders = shOrderDao.selectShOrder(shOrderAll1.getId());
						for(ShOrder shOrderAll : shOrders){
							if(shOrderAll.getOrderStatus().equals("1")){
								shOrderDao.updateOrderAllStatus(shOrderAll1.getId());
							}
						}
					}else{
						String orderStatus = shOrder.getOrderStatus();
						if(orderStatus.equals("1")){
							shOrderDao.updateOrderStatus(str2);
						}
					}

				}
	}
}
